package model

import (
	"common/helper"
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
	"github.com/go-redis/redis/v8"
	"strconv"
)

func PlatformRedis(pid string) (PlatJson, error) {

	plat := PlatJson{}
	num, _ := strconv.Atoi(pid)
	num = (num / 100) * 100
	id := strconv.Itoa(num)
	k := fmt.Sprintf("plat:%s", id)
	cmd := meta.MerchantRedis.Get(ctx, k)
	res, err := cmd.Result()
	if err == redis.Nil || err != nil {
		helper.SqlSelectErrLog("get plat:%s", cmd.String())
		return plat, err
	}

	err = json.Unmarshal([]byte(res), &plat)
	if err != nil {
		return plat, err
	}

	return plat, nil
}

type PlatJson struct {
	ID         string `db:"id" json:"id" cbor:"id"`
	Name       string `db:"name" json:"name" cbor:"name"`
	GameType   int    `db:"game_type" json:"game_type" cbor:"game_type"`
	State      int    `db:"state" json:"state" cbor:"state"`
	Maintained int    `db:"maintained" json:"maintained" cbor:"maintained"`
	Seq        int    `db:"seq" json:"seq" cbor:"seq"`
	//Route      int    `db:"route" json:"route" cbor:"route"`
}

func PlatformSql(pid string) (PlatJson, error) {
	data := PlatJson{}
	num, _ := strconv.Atoi(pid)
	num = (num / 100) * 100
	id := strconv.Itoa(num)
	query, _, _ := dialect.From("tbl_platforms").Select(colsPlatform...).Where(g.Ex{"id": id}).Limit(1).ToSQL()
	err := meta.MerchantDB.Get(&data, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), helper.DBErr)
	}

	if err == sql.ErrNoRows {
		return data, errors.New(helper.RecordNotExistErr)
	}

	return data, nil
}
